<template>
    <el-dialog
        v-model="dialogVisible"
        title="导入分组"
        width="30%"
        :before-close="handClose"
    >
        <div>
            <el-form :model="formData" ref="formRef" label-width="80px" :rules="rules">
                <el-form-item label="分组名称" prop="groupID">
                    <el-select v-model="formData.groupID" class="m-2" placeholder="请选择分组">
                        <el-option
                        v-for="item in groupOptions"
                        :key="item.groupID"
                        :label="item.groupName"
                        :value="item.groupID"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="选择文件" prop="file">
                    <div class="chooseFile">
                        <el-button type="primary" @click="chooseFile">
                        上传<el-icon class="el-icon--right"><Upload /></el-icon>
                        </el-button>
                        <input id="file" type="file" v-show="false" @change="onFileChange"/>
                        <div class="filename" >{{formData.fileName}}</div>
                    </div>
                    
                </el-form-item>
            </el-form>
        </div>
        <template #footer>
        <span class="dialog-footer">
            <el-button @click="closeDialog">取消</el-button>
            <el-button type="primary" @click="confirmDialog(formRef)">
            导入
            </el-button>
        </span>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted,reactive, computed, defineProps, defineEmits, watch} from 'vue'
import {useRouter, useRoute} from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { Upload } from '@element-plus/icons-vue'
import EnvApi from '../../../apis/env'
import {useUserStore} from '../../../stores/user'
import { FormValid } from '../../../utils/FormUtils'

const router = useRouter();
const route = useRoute();
const userStore = useUserStore()

const formRef = ref<FormInstance>()
const formData = ref({
    groupID: "",
    file: null,
    fileName: "JSON格式"
});
const groupOptions = ref();

const rules = reactive<FormRules>({
    groupID: [
        { required: true, message: '请选择分组', trigger: 'change' },
    ],
    file: [
        { required: true, message: '请选择文件', trigger: 'change' }
    ],
})

const props = defineProps({
    isShow: Boolean,
    handleUpdated: Function,
})
const emit = defineEmits(['update:isShow']);

const dialogVisible = ref(props.isShow);
watch(()=> props.isShow,() => {
    console.log('props.isShow change', props.isShow);
    dialogVisible.value = props.isShow
});

onMounted(()=>{
    loadData();
})

const loadData = () =>{
    EnvApi.fetchEnvGroup("", 0, 999).then(ret=>{
        if(ret.code == 0){
            groupOptions.value = ret.data.list;
        }else{
            ElMessage({
                type: 'error',
                message: "加载分组失败",
            })
        }
    }).catch(err=>{
        ElMessage({
            type: 'error',
            message: err,
        })
    })
}

const handClose = () =>{
    console.log('handClose');
    emit('update:isShow', false)
}

const closeDialog = () => {
    console.log('closeDialog');
    emit('update:isShow', false)
}

const confirmDialog = (formRef: FormInstance | undefined) => {
    if (!formRef) return;
    FormValid(formRef).then(ret=>{
        return EnvApi.importEnv(formData.value.groupID, formData.value.file);
    }).then(ret=>{
        if(ret.code == 0){
            ElMessage({
                type: 'success',
                message: "添加成功",
            });
            if(props.handleUpdated){
                props.handleUpdated();
            }
            setTimeout(async () => {
                emit('update:isShow', false)
            }, 1500);
        }else{
            ElMessage({
                type: 'error',
                message: "添加失败",
            });
        }
    }).catch(err=>{
        ElMessage({
            type: 'error',
            message: err
        });
    });
    
}

const chooseFile = async ()=>{
    document.getElementById("file")?.click();
}
const onFileChange = (event:any)=>{
    console.log('[ImportEnvDialog]onFileChange', event);
    formData.value.file = event.target.files[0];
    formData.value.fileName = event.target.files[0].name;
}
</script>

<style scoped>
.filename {
    margin-left: 5px;
    color: #999;
}
</style>
